package com.sheng.leetcode.year2023.month07.day31;

import org.junit.Test;

/**
 * @author liusheng
 * @date 2023/07/31
 * <p>
 * 143. 重排链表<p>
 * <p>
 * 给定一个单链表 L 的头节点 head ，单链表 L 表示为：<p>
 * L0 → L1 → … → Ln - 1 → Ln<p>
 * 请将其重新排列后变为：<p>
 * L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …<p>
 * 不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。<p>
 * <p>
 * 示例 1：<p>
 * 输入：head = [1,2,3,4]<p>
 * 输出：[1,4,2,3]<p>
 * <p>
 * 示例 2：<p>
 * 输入：head = [1,2,3,4,5]<p>
 * 输出：[1,5,2,4,3]<p>
 * <p>
 * 提示：<p>
 * 链表的长度范围为 [1, 5 * 10^4]<p>
 * 1 <= node.val <= 1000<p>
 * <p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/reorder-list">143. 重排链表</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class LeetCode0143 {

    @Test
    public void test01() {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
//        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        new Solution().reorderList(head);
        System.out.println(head);
    }
}

class Solution {
    public void reorderList(ListNode head) {
        ListNode listNode = middleNode(head);
        ListNode tail = reverseList(listNode);
        while (tail.next != null) {
            ListNode headPre = head.next;
            ListNode tailPre = tail.next;
            head.next = tail;
            tail.next = headPre;
            head = headPre;
            tail = tailPre;
        }
    }

    public ListNode middleNode(ListNode head) {
        // 利用快慢指针，快指针每次走两步，慢指针每次走一步，所以快指针走的距离为慢指针的两倍，故当快指针遍历到链表末尾时，慢指针指向记为中间节点
        ListNode pointer1 = head, pointer2 = head;
        while (pointer1 != null && pointer1.next != null) {
            pointer2 = pointer2.next;
            pointer1 = pointer1.next.next;
        }
        return pointer2;
    }

    public ListNode reverseList(ListNode head) {
        ListNode ans = null, cur = head;
        while (cur != null) {
            ListNode listNode = cur.next;
            cur.next = ans;
            ans = cur;
            cur = listNode;
        }
        return ans;
    }
}


// Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
